﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DirectPOS.Printer {
  public abstract class Base {
    protected const byte LF = 0x0A;
    protected const byte FF = 0x0C;
    protected const byte CR = 0x0D;
    protected const byte ESC = 0x1B;
    protected const byte GS = 0x1D;
    protected string mPrinterName;
    protected byte mPreCutFeedUnits = 0;
    protected MemoryStream mBuffer = new MemoryStream();

    public virtual void OpenCashDrawer() { }

    public void WriteBytesToBuffer(byte[] aBytes) {
      mBuffer.Write(aBytes, 0, aBytes.Length);
    }

    public abstract void FlushPage();

    // We collect and "spool" on our own to avoid sending a bunch of separate docs to 
    // the printer. We could modifiy RawPrinter as well but this works better.
    public void Commit() {
      FlushPage();

      var xBytes = mBuffer.ToArray();
      RawPrinter.Send(mPrinterName, xBytes);
      mBuffer = new MemoryStream();
    }

    public void WriteLine(string aString) {
      WriteBytesToBuffer(ASCIIEncoding.ASCII.GetBytes(aString));
      WriteBytesToBuffer(new byte[] {CR, LF});
    }

    public void Write(string aString) {
      WriteBytesToBuffer(ASCIIEncoding.ASCII.GetBytes(aString));
    }

    public void CutPaper() {
      CutPaper(mPreCutFeedUnits);
    }

    public abstract void CutPaper(byte aFeedUnits);

  }
}
